package com.sina.interfaces.manage.dao.user;

import com.sina.interfaces.dao.InterFacesDataSourceDao;
import com.sina.interfaces.domain.user.User;
import com.sina.interfaces.domain.user.User_;
import org.hibernate.query.Query;
import org.springframework.stereotype.Repository;

import javax.persistence.NoResultException;
import javax.persistence.Tuple;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * 段浩杰   2017-11-14-13:07
 */
@Repository("userManageDao")
public class UserManageDaoImpl extends InterFacesDataSourceDao implements UserManageDao {

    @Override
    public int delete(Long id) {
        return template.executeWithNativeSession(session -> {
            String hql = "delete from User u where u.id = :id";
            Query query = session.createQuery(hql);
            query.setParameter("id", id);

            return query.executeUpdate();
        });
    }

    @Override
    public User getUser(String name) {
        String hql = "select new User(id,name,lastIp,createTime,userSex,phone,email,status) from User where name=:name";
        return unique(hql, new String[]{"name"}, new Object[]{name});
    }

    @Override
    public List<Map<String, Object>> getUserList(User user) {
        return template.executeWithNativeSession(session -> {

            // 用于构建标准查询，复合选择，表达式，谓词，排序
            CriteriaBuilder builder = session.getCriteriaBuilder();
            //创建一个CriteriaQuery返回一个元组的对象作为结果。
            CriteriaQuery<Tuple> criteriaQuery = builder.createTupleQuery();
            Root<User> root = criteriaQuery.from(User.class);
            criteriaQuery.multiselect(
                    userSelection(root)
            );
            Predicate predicate = userPredicate(user, builder, root);
            criteriaQuery.where(predicate);
            boolean hasLastId = user.getLastId() != null;
            //指定用于排序查询结果的排序表达式
            criteriaQuery.orderBy(
                    builder.desc(root.get(User_.id))
            );
            Query<Tuple> query = session.createQuery(criteriaQuery);
            if (!hasLastId) {
                int first = (user.getPage() - 1) * user.getRows();
                query.setFirstResult(first);
            }
            query.setMaxResults(user.getRows());
            //执行查询 query.getResultList()
            return mapWrapperFromTuple(query.getResultList(), HashMap.class);
        });
    }

    @Override
    public Long getUserCount(User user) {
        return template.executeWithNativeSession(session -> {

            CriteriaBuilder builder = session.getCriteriaBuilder();
            CriteriaQuery<Long> criteriaQuery = builder.createQuery(Long.class);
            Root<User> root = criteriaQuery.from(User.class);
            //根据id查找结果数
            criteriaQuery.select(
                    builder.count(root.get(User_.id))
            );
            //组装查询条件
            criteriaQuery.where(
                    userPredicate(user, builder, root)
            );
            //创建插叙语句
            Query<Long> query = session.createQuery(criteriaQuery);
            long count;
            try {
                //得到结果条数
                count = query.getSingleResult();
            } catch (NoResultException e) {
                count = 0;
            }
            return count;
        });
    }


    /**
     * 查询条件组装类
     *
     * @param user
     * @param builder
     * @param root
     * @return
     */
    protected Predicate userPredicate(User user, CriteriaBuilder builder
            , Root<User> root) {
        List<Predicate> list = new ArrayList<>(4);

        if (user.getLastId() != null) {
            list.add(
                    builder.lt(root.get(User_.id), user.getLastId())
            );
        }

        //用户名字
        if (user.getName() != null) {
            list.add(
                    builder.like(root.get(User_.name), "%" + user.getName() + "%")
            );
        }

        //用户手机号
        if (user.getPhone() != null) {
            list.add(
                    builder.like(root.get(User_.phone), "%" + user.getPhone() + "%")
            );
        }
        //用户邮箱
        if (user.getEmail() != null) {
            list.add(
                    builder.like(root.get(User_.email), "%" + user.getEmail() + "%")
            );
        }

        if (user.getStatus() != null) {
            list.add(
                    builder.equal(root.get(User_.status), user.getStatus())
            );
        }


        if (user.getCreateStart() != null) {
            list.add(
                    builder.greaterThanOrEqualTo(root.get(User_.createTime), user.getCreateStart())
            );
        }

        if (user.getCreateEnd() != null) {
            list.add(
                    builder.lessThanOrEqualTo(root.get(User_.createTime), user.getCreateEnd())
            );
        }

        return builder.and(
                list.toArray(new Predicate[list.size()])
        );
    }


    /**
     * 所要查询的字段组装类
     *
     * @param root
     * @return
     */
    protected List<Selection<?>> userSelection(Root<User> root) {

        List<Selection<?>> list = new ArrayList<>(12);
        /**
         * 五条一组
         */
        list.add(root.get(User_.id).as(Long.class).alias("id"));//id
        list.add(root.get(User_.name).alias("name"));//用户名
        list.add(root.get(User_.createTime).alias("createTime"));//创建时间
        list.add(root.get(User_.lastIp).alias("lastIp"));//最后登录ip
        list.add(root.get(User_.userSex).alias("userSex"));//性别

        list.add(root.get(User_.phone).alias("phone"));//手机号
        list.add(root.get(User_.email).alias("email"));//邮箱
        list.add(root.get(User_.status).alias("status"));//状态

        return list;
    }

}
